import { Middleware, IMiddleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';

@Middleware()
export class ErrorMiddleware implements IMiddleware<Context, NextFunction> {
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      try {
        // 执行请求处理
        await next();
      } catch (error) {
        // 记录错误日志
        ctx.logger.error(`[ERROR] ${ctx.method} ${ctx.url} - Error: ${error.message}`, {
          stack: error.stack, // 记录堆栈信息
        });
        // 将错误传递给下游的错误处理中间件
        ctx.throw(error.status || 500, error.message);
      }
    };
  }

  static getName(): string {
    return 'error';
  }
}
